


window.jsfetch = async function(url, options) {
    // const js_fetch_response= new Module.JsFetchResponse;
    const response = await fetch(url, options);
    console.log(response);
    // js_fetch_response.SetStatusCode(response.status);

    let headers = '';
    response.headers.forEach((value, name) => {
        // js_fetch_response.AddHeader(name, value);
        headers += `${name}: ${value}\n`;
    });
    // js_fetch_response.SetFinished(true);

    const result = {status: response.status, headers: headers, body: ""};
    const content_type = response.headers.get('content-type');
    if (content_type.includes('application/json')) {
        result.body = JSON.stringify(await response.json());
        // js_fetch_response.AppendBody(JSON.stringify(json));
    } else if (content_type.includes('text/plain')) {
        result.body = await response.text();
        // js_fetch_response.AppendBody(await response.text());
    } else if (content_type.includes('image/')) {
        result.body = await response.blob();
        // js_fetch_response.AppendBody(await response.blob());
    } else {
        const reader = response.body.getReader();
        if (reader) {
            result.stream = true;
            result.body = async function() {
                return await reader.read();
            }
        }
    }

    return result;
};